// 路由
import {
	RouterMount,
	createRouter
} from 'uni-simple-router'
import store from '@/codecat/store'
import {
	getToken,
	removeToken,
	setToken
} from "@/codecat/utils/auth";

const router = createRouter({
	platform: 'h5',
	applet: {
		animationDuration: 0 //默认 300ms 
	},
	// 通配符，非定义页面，跳转404
	routes: [...ROUTES,
		{
			path: '*',
			redirect: (to) => {
				return {
					name: '404'
				}
			}
		},
	]
});

router.beforeEach((to, from, next) => {
	// 为了方便本地调试，从正式环境获取token
	// if (!getToken()) {
	// 	setToken(
	// 		'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnYW1lLmNuIiwiYXVkIjoiZ2FtZS5jbiIsImlhdCI6MTc2MzYzNjUxNywibmJmIjoxNzYzNjM2NTE3LCJleHAiOjE3NjQyNDEzMTcsImV4dGVuZCI6eyJpZCI6MTAwMTIsInVzZXJuYW1lIjoiMTc3MjIzMzAwOTAiLCJyZWFsbmFtZSI6ImppYWp1biIsInJvbGVfaWQiOjAsInBob25lIjoiMTc3MjIzMzAwOTAiLCJlbWFpbCI6IiIsImNyZWF0ZV90aW1lIjoiMjAyNS0wOS0xMyAxNTo1Nzo1NCIsInVzZXJfdHlwZSI6InRlYWNoZXIiLCJzY2hvb2xfaWRzIjoiMzciLCJzY2hvb2xfcm9sZV9saXN0IjoiW3tcInNjaG9vbF9pZFwiOjM3LFwicm9sZV9pZFwiOjJ9XSIsIm9wZW5pZCI6Im9pUDdXN1R5eHYxNzE0NTJMSmF0NEYtZ28xb3cifX0.Xu-6enpEALqOfnsUR9rU4fIqrjOqOMkqImUaKtpkAEE'
	// 	)
	// }


	if (getToken()) {
		if (to.path === "/pages/login/index") {
			next('/');
		} else {
			if (!store.getters.belong?.length) {
				store.dispatch("GetSchool").then(belong => {
					next();
				})
			} else next();
		}
	} else {
		if (!to.meta?.auth) {
			removeToken()
			next();
		} else {
			// LogOut 本身就有 removeToken
			store.dispatch("LogOut").then(() => {
				next({
					path: '/login',
					replace: true
				});
			})
		}
	}
});

export {
	router,
	RouterMount,
}